<!--
 * @Author: lihaogn
 * @Date: 2022-05-17 21:25:53
 * @LastEditTime: 2022-05-18 00:22:58
 * @LastEditor: lihaogn
 * @Description: 预览选择的图片
 * @FilePath: \lix-vue2-demos\src\views\demo\apply\file-visit\modules\FilePreview.vue
-->
<template>
  <el-card>
    <div slot="header">
      <span>预览选择的图片</span>
    </div>
    <div>
      <input
        type="file"
        ref="fileElemRef"
        multiple
        accept="image/*"
        style="display:none"
        @change="handleFiles"
      />
      <el-button @click="selectFile">Select some images</el-button>
      <div class="img-box">
        <img
          v-for="(item, index) in fileList"
          :key="item.id"
          :src="item.src"
          :alt="item.alt"
          width="100"
          height="100"
        />
      </div>
    </div>
  </el-card>
</template>

<script>
import { generateId } from '@/utils/common'
export default {
  data() {
    return {
      fileList: []
    }
  },
  beforeDestroy() {
    this.fileList.forEach(file => {
      if (file.src) {
        URL.revokeObjectURL(file.src)
      }
    })
  },
  methods: {
    /**
     * @author: lihaogn
     * @Date: 2022-05-17 15:42:30
     * @description: 选择按钮点击事件
     * @return {*}
     */
    selectFile() {
      this.$refs.fileElemRef.click()
    },
    /**
     * @author: lihaogn
     * @Date: 2022-05-18 00:21:41
     * @description: 处理文件
     *     使用 createObjectURL 处理图片地址
     * @param undefined
     * @return {*}
     */

    handleFiles(e) {
      let files = e.target.files

      for (let i = 0; i < files.length; i++) {
        let file = files[i]
        let imageType = /^image\//

        if (!imageType.test(file.type)) {
          continue
        }

        file.id = generateId()
        file.alt = file.name
        file.src = URL.createObjectURL(file)
      }
      this.fileList = files
    }
    /**
     * @author: lihaogn
     * @Date: 2022-05-18 00:21:38
     * @description: 处理文件
     *     使用 readAsDataURL 处理图片地址
     * @param undefined
     * @return {*}
     */
    // handleFiles(e) {
    //   let files = e.target.files

    //   for (let i = 0; i < files.length; i++) {
    //     let file = files[i]
    //     let imageType = /^image\//

    //     if (!imageType.test(file.type)) {
    //       continue
    //     }

    //     file.id = generateId()
    //     file.alt = file.name

    //     let reader = new FileReader()
    //     reader.onload = (function(fileList, file) {
    //       return function(e) {
    //         file.src = e.target.result
    //         fileList.push(file)
    //       }
    //     })(this.fileList, file)
    //     reader.readAsDataURL(file)
    //   }
    // }
  }
}
</script>

<style lang="less" scoped></style>
